# oss_uploader.py
import os
import oss2
import time
import logging
from datetime import datetime
from oss2 import Auth, Bucket, exceptions
import uuid

logger = logging.getLogger(__name__)


class FreeOSSUploader:
    def __init__(self):
        """初始化免费OSS上传器"""
        self.access_key_id = "LTAI5tG4A6DzaQ8RuW7aSq59"
        self.access_key_secret = "aBK7ijCmwSspSqhd9JuR4rl2oeE45x"

        # 免费用户推荐使用的地域
        self.endpoint = 'oss-cn-beijing.aliyuncs.com'  # 华东1（杭州）
        self.bucket_name = f"ai-arm-controller-oss-1"

        self._validate_credentials()
        self.auth = Auth(self.access_key_id, self.access_key_secret)

    def _validate_credentials(self):
        """验证凭证"""
        if not all([self.access_key_id, self.access_key_secret]):
            raise ValueError("请设置环境变量: ALIYUN_AK_ID, ALIYUN_AK_SECRET")

    def create_free_bucket(self):
        """创建免费的存储桶"""
        try:
            # 创建Bucket实例
            bucket = Bucket(self.auth, self.endpoint, self.bucket_name)

            # 创建存储桶（免费额度内）
            bucket.create_bucket(
                oss2.models.BucketCreateConfig(
                    oss2.BUCKET_ACL_PUBLIC_READ,  # 公有读（仅用于测试）
                    oss2.models.BucketCreateConfig.STANDARD  # 标准存储
                )
            )

            logger.info(f"创建存储桶成功: {self.bucket_name}")
            return bucket

        except exceptions.OssError as e:
            logger.error(f"创建存储桶失败: {e}")
            # 如果存储桶已存在，直接使用
            if e.status == 409:  # BucketAlreadyExists
                logger.info(f"存储桶已存在，直接使用: {self.bucket_name}")
                return Bucket(self.auth, self.endpoint, self.bucket_name)
            raise

    def upload_file(self, local_file_path, expiration_hours=1):
        """
        上传文件到免费OSS并生成临时访问链接

        Args:
            local_file_path: 本地文件路径
            expiration_hours: 链接有效期（小时）

        Returns:
            str: 可公开访问的URL
        """
        try:
            # 检查文件大小（免费额度限制）
            file_size = os.path.getsize(local_file_path)
            if file_size > 5 * 1024 * 1024 * 1024:  # 5GB限制
                raise ValueError("文件大小超过免费额度限制（5GB）")

            # 创建存储桶
            bucket = self.create_free_bucket()

            # 生成唯一的对象名
            filename = os.path.basename(local_file_path)
            file_ext = os.path.splitext(filename)[1]
            object_name = f"speech/{datetime.now().strftime('%Y%m%d')}/{uuid.uuid4().hex}{file_ext}"

            logger.info(f"开始上传文件: {local_file_path} -> {object_name}")

            # 上传文件
            result = bucket.put_object_from_file(object_name, local_file_path)

            if result.status == 200:
                # 生成签名URL（有效期1小时）
                signed_url = bucket.sign_url('GET', object_name, expiration_hours * 3600)
                logger.info(f"文件上传成功: {signed_url}")
                return signed_url
            else:
                raise Exception(f"上传失败，状态码: {result.status}")

        except Exception as e:
            logger.error(f"文件上传失败: {e}")
            raise

    def cleanup(self):
        """清理测试文件（避免超出免费额度）"""
        try:
            bucket = Bucket(self.auth, self.endpoint, self.bucket_name)

            # 列出并删除所有对象
            for obj in oss2.ObjectIterator(bucket):
                bucket.delete_object(obj.key)
                logger.info(f"删除对象: {obj.key}")

            logger.info("清理完成")

        except Exception as e:
            logger.error(f"清理失败: {e}")


oss = FreeOSSUploader()
oss.upload_file(r"/home/suke/tangqi/ai_arm_controller/audio_file/1.mp3")